//
//  ObserverCustomBindViewController.swift
//  iOS-RxSwift-Tutorials_Example
//
//  Created by mengru.tian on 2020/9/17.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

// 4.Observer - 自定义可绑定属性
class ObserverCustomBindViewController: UIViewController {
    
    @IBOutlet weak var label: UILabel!
    
    private let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "Observer - 自定义可绑定属性"
        self.view.backgroundColor = UIColor.white

        // testBind()
        testBind2()
    }

}

extension UILabel {
    public var fontSize: Binder<CGFloat> {
        return Binder(self) { label, fontSize in
            label.font = UIFont.systemFont(ofSize: fontSize)
        }
    }
}

extension Reactive where Base: UILabel {
    public var fontSize: Binder<CGFloat> {
        return Binder(self.base) { label, fontSize in
            label.font = UIFont.systemFont(ofSize: fontSize)
        }
    }
}

extension ObserverCustomBindViewController {
    
    // 方式一：通过对 UI 类进行扩展
    func testBind() {
        //Observable序列（每隔0.5秒钟发出一个索引数）
        let observable = Observable<Int>.interval(RxTimeInterval.milliseconds(500), scheduler: MainScheduler.instance)
        observable
            .map { CGFloat($0) }
            .bind(to: label.fontSize) //根据索引数不断变放大字体
            .disposed(by: disposeBag)
    }
    
    // 方式二：通过对 Reactive 类进行扩展
    func testBind2() {
        //Observable序列（每隔0.5秒钟发出一个索引数）
        let observable = Observable<Int>.interval(RxTimeInterval.milliseconds(500), scheduler: MainScheduler.instance)
        observable
            .map { CGFloat($0) }
            .bind(to: label.rx.fontSize) //根据索引数不断变放大字体
            .disposed(by: disposeBag)
    }
}
